package life;

// 43.字符串相乘（大数相乘）
public class BigMultiply {

    public String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        String res = "0";

        for (int i = num2.length() - 1; i >= 0; i--) {
            int carry = 0; // 进位数
            StringBuffer temp = new StringBuffer();
            // 补0
            for (int j = 0; j < num2.length() - 1 - i; j++) {
                temp.append(0);
            }
            int n2 = num2.charAt(i) - '0';
            for (int j = num1.length() - 1; j >= 0 || carry != 0; j--) {

                int n1 = j < 0 ? 0 : num1.charAt(j) - '0';
                int p = (n1 * n2 + carry) % 10;
                temp.append(p);
                carry = (n1 * n2 + carry) / 10;
            }
            res = add(res, temp.reverse().toString());
        }
        return res;
    }

    private String add(String a, String b) {
        StringBuffer stringBuffer = new StringBuffer();
        int carry = 0;
        for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0 || carry != 0; i--, j--) {
            int n1 = i < 0 ? 0 : a.charAt(i) - '0';
            int n2 = j < 0 ? 0 : b.charAt(j) - '0';
            int sum = (n1 + n2 + carry) % 10;
            stringBuffer.append(sum);
            carry = (n1 + n2 + carry) / 10;
        }
        return stringBuffer.reverse().toString();
    }


}


